package com.mission.schedule.my160920;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.mission.schedule.applcation.App;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.my160920.bean.FriendBackBean;
import com.mission.schedule.my160920.bean.FriendBean;
import com.mission.schedule.my160920.bean.FriendDeleteScheduleBean;
import com.mission.schedule.my160920.bean.FriendDownAllScheduleBean;
import com.mission.schedule.my160920.bean.FriendDownBackBean;
import com.mission.schedule.utils.SharedPrefUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liwei on 2016/9/22.
 */
public class UpdataFrendAndCalender {

    SharedPrefUtil sharedPrefUtil;
    Context contexts;
    String persondowntime;
    String downtime;
    String userid;


    List<Integer> uid = new ArrayList<>();

    public UpdataFrendAndCalender(Context context){
        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        contexts = context;
        persondowntime = sharedPrefUtil.getString(context,ShareFile.USERFILE,ShareFile.PERSONDOWNTIME,"2016-01-01");
        downtime = sharedPrefUtil.getString(context,
                ShareFile.USERFILE, ShareFile.QIANDAODOWNDATE,
                "2016-01-01");
        userid = sharedPrefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.USERID, "");
    }


    private void sendMess(Handler handler, int what){
        Message message = new Message();
        message.what = what;
        handler.sendMessage(message);
    }


    /**
     * 下载好友信息
     */
    public void DownFrend(final Handler handler) {
        StringRequest stringRequest = new StringRequest(Method.POST, "http://121.40.19.103/timetable/appFrends_findFrendsSay.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();

                                FriendBackBean friendBackBean = gson.fromJson(result, FriendBackBean.class);
                                if (friendBackBean.status == 0) {


                                    List<FriendBean> friendBeanList = friendBackBean.list;

                                    for (FriendBean bean : friendBeanList) {
                                        App.getDBcApplication().insertFriendsList(bean);
                                    }

                                    DownFrendCalender(handler);
                                }else {
                                    sendMess(handler,4);
                                }


                            } catch (Exception e) {
                                e.printStackTrace();
                                sendMess(handler,4);
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userid);// "52432"
                map.put("updateTime", persondowntime);//"2015-01-01 00:00:00"
                return map;
            }
        };
        stringRequest.setTag("friend");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }


    /**
     * 下载所有日程信息
     */
    private void DownFrendCalender(final Handler handler) {
        StringRequest stringRequest = new StringRequest(Method.POST, "http://121.40.19.103/timetable/appFrends_downFrendsCalendar.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();

                                FriendDownBackBean findFrendsSayBean = gson.fromJson(result, FriendDownBackBean.class);
                                if (findFrendsSayBean.status == 0) {

                                    sharedPrefUtil
                                            .putString(
                                                    contexts,
                                                    ShareFile.USERFILE,
                                                    ShareFile.TELEPHONE,
                                                    findFrendsSayBean.downTime);

                                    List<FriendDownAllScheduleBean> firendDownBeanList = findFrendsSayBean.list;
                                    List<FriendDeleteScheduleBean> friendDeleteScheduleBeanList = findFrendsSayBean.delList;

                                    for (FriendDownAllScheduleBean bean : firendDownBeanList) {
                                        App.getDBcApplication().insertFriendSchedule(bean);
                                    }

                                    for (FriendDeleteScheduleBean bean : friendDeleteScheduleBeanList) {
                                        App.getDBcApplication().deleteFriendSchedule(bean.dataId);
                                    }
                                    sendMess(handler,3);
                                }else {
                                    sendMess(handler,4);
                                }


                            } catch (Exception e) {
                                e.printStackTrace();
                                sendMess(handler,4);
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userid);// "52432"
                map.put("updateTime", persondowntime);//"2015-01-01 00:00:00"
                return map;
            }
        };
        stringRequest.setTag("allfriendcalender");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }

    /**
     * 将数据库的数据转换为一个Bean
     */
    public List<FrendBean> DBtoAllList() {

        List<FrendBean> frendBeanList = new ArrayList<>();

        List<FriendBean> friendBeanList = App.getDBcApplication().backFriendsList(userid);
        List<FriendDownAllScheduleBean> friendDownAllScheduBeanList = App.getDBcApplication().getAllFriendSchedule();

        for (int i = 0; i < friendBeanList.size(); i++) {
            FrendBean frendBean = new FrendBean();
            frendBean.setF_uNickName(friendBeanList.get(i).uNickName);
            frendBean.setF_uPersontag(friendBeanList.get(i).uPersontag);
            frendBean.setF_uPortrait(friendBeanList.get(i).uPortrait);
            frendBean.setViewType(1);
            frendBean.setF_uid(friendBeanList.get(i).uid);
            frendBean.setUid(friendBeanList.get(i).uid);
            frendBeanList.add(frendBean);
            for (int j = 0; j < friendDownAllScheduBeanList.size(); j++) {
                if (friendBeanList.get(i).cpId.equals(friendDownAllScheduBeanList.get(j).cpId)) {
                    uid.add(j);
                }

            }
            if (uid.size() <= 0 || uid == null) {
                FrendBean frendBean4 = new FrendBean();
                frendBean4.setUid(friendBeanList.get(i).uid);
                frendBean4.setViewType(4);
                frendBeanList.add(frendBean4);
            } else {
                for (int u = 0; u < uid.size(); u++) {
                    FrendBean frendBean2 = new FrendBean();
                    frendBean2.setMessage(friendDownAllScheduBeanList.get(uid.get(u)).message);
                    frendBean2.setDownNum(friendDownAllScheduBeanList.get(uid.get(u)).downNum);
                    frendBean2.setEndState(friendDownAllScheduBeanList.get(uid.get(u)).endState);
                    frendBean2.setChangTime(friendDownAllScheduBeanList.get(uid.get(u)).changTime);
                    frendBean2.setF_uNickName(friendBeanList.get(i).uNickName);
                    frendBean2.setF_uPortrait(friendBeanList.get(i).uPortrait);
                    frendBean2.setCdate(friendDownAllScheduBeanList.get(uid.get(u)).cdate);
                    frendBean2.setRepDisplayTime(friendDownAllScheduBeanList.get(uid.get(u)).repDisplayTime);
                    frendBean2.setCPostpone(friendDownAllScheduBeanList.get(uid.get(u)).CPostpone);
                    if (u == uid.size() - 1) {
                        frendBean2.setViewType(3);
                    } else {
                        frendBean2.setViewType(2);
                    }
                    frendBean2.setUid(friendDownAllScheduBeanList.get(uid.get(u)).uid);
                    frendBeanList.add(frendBean2);
                }

            }
            uid.clear();

        }
        return frendBeanList;
    }
}
